﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WorkBasket.Data.Entities;
using WorkBasket.Data.Repository;
using WorkBasket.Infrastructure;
using WorkBasket.Models;

namespace WorkBasket.Controllers.Api
{
    [Authorize]
    public class InstanceHistoryController : ApiController
    {


        private SOC soc = new SOC(new MyContext());
        [Route("api/InstanceHistory/save")]
        public IHttpActionResult Post([FromBody] InstanceHistory value)
        {
            try
            {

                InstanceHistory ih;


                Step step =  soc.Steps.GetByID(value.StepID);
                ProcessVersion pv = soc.ProcessVersions.GetByID(step.ProcessVersionID);
                

                if (value.InstanceID == 0)
                {
                    Instance inst = new Instance(0, (int)pv.WorkflowID, pv.ProcessVersionID);
                    soc.Instances.Add(inst);
                    soc.CommitChanges();
                    value.InstanceID = inst.InstanceID;
                    ih = soc.Execute<InstanceHistory>("CreateProcessPath @processVersionID,@InstanceID",
                                new SqlParameter("processVersionID", pv.ProcessVersionID),
                                new SqlParameter("InstanceID", value.InstanceID)).FirstOrDefault();
                    soc.CommitChanges();//to pick up the inserts the proc made
                    value.InstanceHistoryID = ih.InstanceHistoryID;
                    
                }
                 

                value.TimeStamp = DateTime.Now;
                if (value.InstanceHistoryID == 0)
                {
                    soc.InstanceHistorys.Add(value);  //should never go in here so eventually throw an error instead
                }
                else
                {
                    soc.InstanceHistorys.Update(value);
                }

                soc.CommitChanges();
                return Json(new DataReturn("Saved", value));
            }
            catch (Exception e)
            {
                return new System.Web.Http.Results.ExceptionResult(e, this);
            }
        }
    }
}
